Page({
  data: {
    record: null,
    statusOptions: ['处理中', '已完成', '已取消'],
    statusValues: ['0', '1', '2'],
    statusIndex: 0
  },

  onLoad(options) {
    const { id } = options;
    const transactions = wx.getStorageSync('transactions') || [];
    const record = transactions.find(item => item.id == id);

    if (record) {
      // 根据数字状态值设置状态索引
      const statusIndex = this.data.statusValues.indexOf(record.status);
      this.setData({
        record,
        statusIndex: statusIndex !== -1 ? statusIndex : 0
      });
    } else {
      wx.showToast({
        title: '记录不存在',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 处理输入变化
  onOriginalAmountChange(e) {
    const originalAmount = parseFloat(e.detail.value) || 0;
    const rate = this.data.record.rate;
    const amount = this.calculateAmount(originalAmount, rate);

    this.setData({
      'record.originalAmount': originalAmount,
      'record.amount': amount
    });
  },

  onRateChange(e) {
    const rate = parseFloat(e.detail.value) || 0;
    const originalAmount = this.data.record.originalAmount;
    const amount = this.calculateAmount(originalAmount, rate);

    this.setData({
      'record.rate': rate,
      'record.amount': amount
    });
  },

  onStatusChange(e) {
    const statusIndex = parseInt(e.detail.value);
    this.setData({
      statusIndex,
      'record.status': this.data.statusValues[statusIndex]
    });
  },

  onNoteChange(e) {
    this.setData({
      'record.note': e.detail.value
    });
  },

  // 计算实际金额
  calculateAmount(originalAmount, rate) {
    return parseFloat((originalAmount * (1 - rate)).toFixed(2));
  },

  // 数据验证
  validateForm() {
    const { record } = this.data;

    if (!record.originalAmount || record.originalAmount <= 0) {
      wx.showToast({
        title: '请输入有效的原始金额',
        icon: 'none'
      });
      return false;
    }

    if (record.rate < 0 || record.rate >= 1) {
      wx.showToast({
        title: '汇率必须在0到1之间',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 保存记录
  saveRecord() {
    if (!this.validateForm()) return;

    try {
      const transactions = wx.getStorageSync('transactions') || [];
      const index = transactions.findIndex(item => item.id === this.data.record.id);

      if (index !== -1) {
        // 更新现有记录
        transactions[index] = {
          ...this.data.record,
          updateTime: new Date().toISOString()
        };

        wx.setStorageSync('transactions', transactions);

        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });

        // 返回上一页并刷新列表
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        if (prevPage && prevPage.loadTransactions) {
          prevPage.loadTransactions();
        }

        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: '记录不存在',
          icon: 'none'
        });
      }
    } catch (e) {
      console.error('保存记录失败:', e);
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
})
